package org.alex.samples.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.alex.samples.model.ExamTest;
import org.alex.samples.model.ExamTestType;
import org.alex.samples.model.Subject;
import org.alex.samples.service.IExamScoreService;
import org.alex.samples.service.IExamTestService;
import org.alex.samples.service.IExamTestType;
import org.alex.samples.service.ISubjectService;
import org.alex.samples.vo.CommonMessageResultVO;
import org.alex.samples.vo.ExamTestTypeVO;
import org.alex.samples.vo.ExamTestVO;
import org.alex.samples.vo.SubjectVO;
import org.alex.samples.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ExamTestController {
	
	@Autowired
	IExamScoreService examScoreService;
	@Autowired 
	IExamTestService examTestService;
	
	@Autowired
	ISubjectService subjectService;
	
	@Autowired
	IExamTestType examTestTypeService;
	
	@RequestMapping("/examTest")
	public String users(Model model) throws Exception{
		List<ExamTest> list = examTestService.FindAllExamTest();
		List<ExamTestVO> VOlist = new ArrayList<>();
		for(ExamTest examTest:list){
			ExamTestVO examTestVO = new ExamTestVO();
			examTestVO.setAnswer(examTest.getAnswer());
			examTestVO.setChooseA(examTest.getChooseA());
			examTestVO.setChooseB(examTest.getChooseB());
			examTestVO.setChooseC(examTest.getChooseC());
			examTestVO.setChooseD(examTest.getChooseD());
			examTestVO.setContent(examTest.getContent());
			examTestVO.setSubId(examTest.getSubId());
			examTestVO.setId(examTest.getId());
			
			ExamTestTypeVO examTestTypevo = new ExamTestTypeVO();
			ExamTestType examTestType = examTest.getExamTestType();
			examTestTypevo.setId(examTestType.getId());
			examTestTypevo.setTestType(examTestType.getTestType());
			examTestTypevo.setTestTypeScore(examTestType.getTestTypeScore());
			examTestVO.setExamTestType(examTestTypevo);
			
			SubjectVO subject = subjectService.FindSubjectById(examTest.getSubId());
			if(subject == null){
				throw new Exception("找不到该科目");
			}
			examTestVO.setSubName(subject.getName());
			VOlist.add(examTestVO);
			
			
			
			
		}
		model.addAttribute("examTestVOList", VOlist);
		
		//查找全部考试类型

		List<ExamTestType> testTypeList = examTestTypeService.findAllExamTestType();
		model.addAttribute("testTypeList", testTypeList);
		
		//查找全部科目

		List<Subject> subjectList = subjectService.FindAllSubject();
		model.addAttribute("subjectList", subjectList);
		
		return "examtest/examTestList";
	}
	

	
	@ResponseBody
	@RequestMapping(value = "/getTestById", method = RequestMethod.POST)
	public ExamTestVO findExamTestByid(Integer testId)throws Exception{
		 ExamTest examTest= examTestService.FindExamTestById(testId);
		 ExamTestVO VOresult = new ExamTestVO();
		 if(examTest.getId() == null){
			 throw new Exception("没有找到该考试");
		 }else if(subjectService.FindSubjectById(examTest.getSubId()) == null){
			 throw new Exception("没有找到该科目");
		 }else{
			 VOresult.setSubName(subjectService.FindSubjectById(examTest.getSubId()).getName()); 
		 }
		 
		 VOresult.setId(testId);
//		 Subject subject = subjectService.FindSubjectById(examTest.getSubId());

//		 if(subject == null){

//			 throw new Exception("没有找到该科目");

//		 }

//		 VOresult.setSubName(subject.getName());

		 VOresult.setContent(examTest.getContent());
		 VOresult.setChooseA(examTest.getChooseA());
		 VOresult.setChooseB(examTest.getChooseB());
		 VOresult.setChooseC(examTest.getChooseC());
		 VOresult.setChooseD(examTest.getChooseD());
		 VOresult.setAnswer(examTest.getAnswer());
		 VOresult.setSubId(examTest.getSubId());
		 VOresult.setExamTestType(new ExamTestTypeVO());
		 VOresult.getExamTestType().setId(examTest.getExamTestType().getId());
		 VOresult.getExamTestType().setTestType(examTest.getExamTestType().getTestType());
		 VOresult.getExamTestType().setTestTypeScore(examTest.getExamTestType().getTestTypeScore());
		return VOresult;
		
	}
	
	@ResponseBody
	@RequestMapping(value = "/openAddTest", method = RequestMethod.POST)
	public List<ExamTestType> openAddTest() throws Exception {
		return null;
	}
	
	@ResponseBody
	@RequestMapping(value = "/addTest", method = RequestMethod.POST)
	public CommonMessageResultVO addTest(@Valid ExamTestVO examTestVO,BindingResult bindingResult) throws Exception {
		CommonMessageResultVO resultVO = new CommonMessageResultVO();
		resultVO.setSuccess(false);
		try{
		ExamTest examTest = new ExamTest();
		examTest.setAnswer(examTestVO.getAnswer());
		examTest.setChooseA(examTestVO.getChooseA());
		examTest.setChooseB(examTestVO.getChooseB());
		examTest.setChooseC(examTestVO.getChooseC());
		examTest.setChooseD(examTestVO.getChooseD());
		examTest.setContent(examTestVO.getContent());
		examTest.setSubId(examTestVO.getSubId());
		ExamTestType examTestType = new ExamTestType();
		examTestType = examTestTypeService.findById(examTestVO.getExamTestTypeId());
//		if(examTestType == null){

//			throw new Exception("找不到该考试类型");

//		}

		examTest.setExamTestType(examTestType);
		examTestService.creatExamTest(examTest);
		resultVO.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultVO;
	}
	@ResponseBody
	@RequestMapping(value = "/saveEditTest", method = RequestMethod.POST)
	public CommonMessageResultVO saveEditTest(@Valid ExamTestVO examTestVO,BindingResult bindingResult) throws Exception{
		CommonMessageResultVO resultVO = new CommonMessageResultVO();
		resultVO.setSuccess(false);
		try{
		ExamTest examTest = new ExamTest();
		examTest.setId(examTestVO.getId());
		examTest.setAnswer(examTestVO.getAnswer());
		examTest.setChooseA(examTestVO.getChooseA());
		examTest.setChooseB(examTestVO.getChooseB());
		examTest.setChooseC(examTestVO.getChooseC());
		examTest.setChooseD(examTestVO.getChooseD());
		examTest.setContent(examTestVO.getContent());
		examTest.setSubId(examTestVO.getSubId());
		ExamTestType examTestType = new ExamTestType();
		examTestType = examTestTypeService.findById(examTestVO.getExamTestTypeId());
		examTest.setExamTestType(examTestType);
		examTestService.editExamTest(examTest);
		resultVO.setSuccess(true);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return resultVO;
	}
	@ResponseBody
	@RequestMapping(value = "/deleteTest", method = RequestMethod.POST)
	public CommonMessageResultVO deleteTest(Integer testId) throws Exception {
		CommonMessageResultVO resultVO = new CommonMessageResultVO();
		resultVO.setSuccess(false);
		try{
		examTestService.deleteExamTest(testId);
		resultVO.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultVO;
	}
	
	@RequestMapping(value = "/toExamTest/{id}")
	public String toExamTest(Model model,HttpSession session,@PathVariable Integer id) throws Exception{
		UserVO uservo = (UserVO) session.getAttribute("user");
		if(uservo.getRole() == 3){
			List<ExamTest> list= examTestService.FindExamTestListBySubjectId(id);
			List<ExamTestVO> rsList = new ArrayList<>();
			for(ExamTest examTest:list){
				ExamTestVO examTestvo = new ExamTestVO();
				examTestvo.setAnswer(examTest.getAnswer());
				examTestvo.setChooseA(examTest.getChooseA());
				examTestvo.setChooseB(examTest.getChooseB());
				examTestvo.setChooseC(examTest.getChooseC());
				examTestvo.setChooseD(examTest.getChooseD());
				examTestvo.setContent(examTest.getContent());
				examTestvo.setId(examTest.getId());
				
				ExamTestTypeVO examTestTypevo = new ExamTestTypeVO();
				examTestTypevo.setId(examTest.getExamTestType().getId());
				examTestTypevo.setTestType(examTest.getExamTestType().getTestType());
				examTestTypevo.setTestTypeScore(examTest.getExamTestType().getTestTypeScore());
				examTestvo.setExamTestType(examTestTypevo);
				
				rsList.add(examTestvo);
			}
			int testcount = rsList.size();
			SubjectVO subjectvo = subjectService.FindSubjectById(id);
			int count = subjectvo.getCount();//题目数量

			List<ExamTestVO> testList = new ArrayList<>();//考卷

			int st = 0 ; //生成试卷的总成绩

			for(int j =0;st != subjectvo.getScore(); j++){
			st=0;
			List<Integer> testnumberlist = this.getRandomNumber(count, testcount);
			testList = new ArrayList<>();
			for(Integer i : testnumberlist){
				ExamTestVO e = rsList.get(i);
				testList.add(e); //把题目加入考卷

				st += e.getExamTestType().getTestTypeScore();
				
			}
			}
			model.addAttribute("testSubject", subjectvo);
			model.addAttribute("testList", testList);
			return "examtest/studentExamTest";
		}
		return null;
	}
	
	@ResponseBody
	@RequestMapping("testtoExamTest")
	public CommonMessageResultVO testtoExamTest(Integer subjectId, HttpSession session){
		System.out.println("考试科目ID:"+subjectId);
		CommonMessageResultVO rs = new CommonMessageResultVO();
		rs.setSuccess(false);
		UserVO uservo = (UserVO) session.getAttribute("user");
		if(uservo.getRole() == 3){
			rs.setSuccess(true);
		}
		return rs;
	}
	
	
	private List<Integer> getRandomNumber(Integer neednumber,Integer max){
	    Random random = new Random();
	    ArrayList<Integer> list = new ArrayList<Integer>();
	    
	    for(int i = 0; i < neednumber;i++){
	      int number = random.nextInt(max);
	      if(!list.contains(number)){
	        list.add(number);
	      }else{
	    	  i--;
	      }
	    }
	    return list;
	}
	
	@ResponseBody
	@RequestMapping("answerTest")
	public CommonMessageResultVO answerTest(Integer subjectId,HttpSession session,HttpServletRequest req) throws Exception{
		CommonMessageResultVO rsvo =  new CommonMessageResultVO();
		rsvo.setSuccess(false);
		String [] answerList = req.getParameterValues("answerList");
		String[] testid = req.getParameterValues("testid");
		int s = 0; //得分

		if(answerList.length == testid.length){
			for(int i = 0 ; i<testid.length;i++){
				Integer testId = Integer.valueOf(testid[i]);
				ExamTest examTest = examTestService.FindExamTestById(testId);
				if(examTest.getAnswer().equals(answerList[i])){
					s += examTest.getExamTestType().getTestTypeScore();//对的题目加相应的分数

				}
			}
			UserVO uservo = (UserVO) session.getAttribute("user");
			examScoreService.saveScoreByUIdSId(uservo.getId(), subjectId, s);
			rsvo.setSuccess(true);
			rsvo.setMessage(s+"");
		}
		
		return rsvo;
	}
}
